﻿using System;
using System.Windows;
using System.Net;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using LantinxShare.Common;

namespace LantinxLBS.Common
{
    public class PathHelper
    {
        public static String GetBasePath()
        {
            String basePath = Application.Current.Host.Source.AbsoluteUri;
            int start = basePath.LastIndexOf("ClientBin");
            basePath = basePath.Substring(0, start);
            //basePath = "http://www.echotian.net/echo/";
            //if (Application.Current.Host.Source.Port == 80)
            //{
            //    basePath = string.Format("{0}://{1}/", Application.Current.Host.Source.Scheme, Application.Current.Host.Source.Host);
            //}
            //else
            //{
            //    basePath = string.Format("{0}://{1}:{2}/", Application.Current.Host.Source.Scheme, Application.Current.Host.Source.Host, Application.Current.Host.Source.Port);

            //}
            return basePath;
        }

        public static string GetData(String url, ResponseEventHandler handler)
        {
            return GetData(url, new Dictionary<string, string>(), handler);
        }
        public static string GetData(String url, String key, String value, ResponseEventHandler handler)
        {
            return GetData(url, new Dictionary<string, string>() { { key, value } }, handler);
        }

        public static string GetData(String url, Dictionary<string, string> postData, ResponseEventHandler handler)
        {

            String basePath = GetBasePath();
            Random random = new Random(DateTime.Now.Second);
            basePath = basePath + url + "&random=" + random.NextDouble();

            CookieContainer cc = new CookieContainer();


            HttpWebRequest baseRequest = WebRequest.CreateHttp(basePath);
            baseRequest.CookieContainer = cc;
            baseRequest.Method = "POST";
            baseRequest.ContentType = "application/x-www-form-urlencoded";
            baseRequest.AllowReadStreamBuffering = true;
            //byte[] byteArray = null;
            //if (!string.IsNullOrEmpty(postData))
            //{

            //    byteArray = Encoding.UTF8.GetBytes(postData); // 转化
            //    baseRequest.ContentLength = byteArray.Length;
            //}
            baseRequest.BeginGetRequestStream((e) =>
            {
                if (e != null)
                {
                    HttpWebRequest request = e.AsyncState as HttpWebRequest;
                    Stream requestStream = request.EndGetRequestStream(e);

                    using (StreamWriter writer = new StreamWriter(requestStream))
                    {
                        if (postData.Count > 0)
                        {
                            List<ParamItem> postDataList = new List<ParamItem>();

                            foreach (var item in postData)
                            {
                                postDataList.Add(new ParamItem() { Key = item.Key, Value = item.Value });
                            }
                            if (postDataList.Count > 0)
                            {

                                writer.Write(System.Windows.Browser.HttpUtility.UrlEncode(postDataList[0].Key) + "=" + System.Windows.Browser.HttpUtility.UrlEncode(postDataList[0].Value));
                                for (int i = 1; i < postData.Count; i++)
                                {
                                    writer.Write("&" + System.Windows.Browser.HttpUtility.UrlEncode(postDataList[i].Key) + "=" + System.Windows.Browser.HttpUtility.UrlEncode(postDataList[i].Value));
                                }
                            }
                        }

                        writer.Flush();
                        writer.Close();
                    }
                    request.BeginGetResponse((e2) =>
                    {
                        if (e2 != null)
                        {
                            WebRequest request3 = e2.AsyncState as WebRequest;
                            WebResponse response = request3.EndGetResponse(e2);

                            using (Stream responseStream = response.GetResponseStream())
                            {
                                String responseResult = String.Empty;
                                try
                                {
                                    StreamReader reader = new StreamReader(responseStream);
                                    responseResult = reader.ReadToEnd();
                                }
                                catch (WebException er)
                                {
                                    Debug.WriteLine(er.Message);
                                }
                                catch (Exception er)
                                {
                                    Debug.WriteLine(responseResult = er.Message);
                                }
                                handler(new ResultObj() { Result = responseResult });
                            }
                        }
                    }, request);
                }
                //newStream.Write(byteArray, 0, byteArray.Length);    //写入参数
                //newStream.Close();
            }, baseRequest);
            // Send the data.


            //downLoadURL = "http://www.echotian.com/echo/AddressPage.aspx?option=getall";
            //wc.DownloadStringAsync(new Uri(basePath, UriKind.Absolute));
            //wc.DownloadStringCompleted += handler;
            return basePath;
        }
    }// end for class
    public delegate void ResponseEventHandler(ResultObj responseResult);
    public class ResultObj
    {
        public String Result { get; set; }

        public List<String[]> ResultList 
        {
            get
            {
                return G.GetSplit(Result);
            }
        }
    }

    public class ParamItem
    {
        public String Key { get; set; }
        public String Value { get; set; }
    }
}
